package com.zhangtai.modules.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.zhangtai.modules.controller.admin.OssUploadService;
import com.zhangtai.modules.dao.ContractUrlDao;
import com.zhangtai.modules.entity.common.ContractUrlEntity;
import com.zhangtai.modules.service.common.ContractUrlService;
import com.zhangtai.utils.IoUtils;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import com.zhangtai.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.util.Date;
import java.util.List;


@RestController
@Slf4j
public class ContractUrlServiceImpl extends ServiceImpl<ContractUrlDao, ContractUrlEntity> implements ContractUrlService {

    @Autowired
    private OssUploadService ossUploadService;
    @Autowired
    private ContractUrlDao contractUrlDao;


    @Override
    public PageResult queryPage(@RequestParam(value = "name",  required = false) String name,
                                                   @RequestParam(value = "blurName",  required = false) String blurName,
                                                   @RequestParam(value = "idCard",  required = false) String idCard,
                                                   @RequestParam(value = "contractName",  required = false) String contractName,
                                                   @RequestParam(value = "signedTimeStart",  required = false) String signedTimeStart,
                                                   @RequestParam(value = "signedTimeStart",  required = false) String signedTimeEnd,
                                                   @RequestParam(value = "type",  required = false) String type,
                                                   @RequestParam(value = "status",  required = false) String status,
                                                   @RequestParam(value = "expiredStartTime",  required = false) String expiredStartTime,
                                                    @RequestParam(value = "expiredEndTime",  required = false) String expiredEndTime,
                                                   @RequestParam(value = "orgIds",  required = false) List<Long> orgIds,
                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                   @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        IPage<ContractUrlEntity> page

              = this.page(
                    new Page<ContractUrlEntity>(pageNum,pageSize),
                    new QueryWrapper<ContractUrlEntity>()
                            .eq(!StringUtils.isEmpty(name),"name",name)
                            .like(!StringUtils.isEmpty(blurName),"name",blurName)
                            .like(!StringUtils.isEmpty(idCard),"id_card",idCard)
                            .like(!StringUtils.isEmpty(contractName),"contract_name",contractName)
                            .ge(!StringUtils.isEmpty(signedTimeStart),"signed_time",signedTimeStart+" 00:00:00")
                            .le(!StringUtils.isEmpty(signedTimeEnd),"signed_time",signedTimeEnd+" 29:59:59")
                            .eq(!StringUtils.isEmpty(type),"type",type)
                            .ge(!StringUtils.isEmpty(expiredStartTime),"contract_end_time",expiredStartTime)
                            .le(!StringUtils.isEmpty(expiredEndTime),"contract_end_time",expiredEndTime)
                            .eq(!StringUtils.isEmpty(status),"status",status)
                            .eq("is_delete",0)
                            .in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds)
                            .eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)
                            //.isNotNull("contract_esign_url")
                           // .isNotNull("contract_oss_url")
                            .orderByDesc("create_time"));


        return new PageResult(page);
    }

    @Override
    public PageResult getPersonContractList(@RequestParam(value = "oid") Long oid,
                                            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize){
        IPage<ContractUrlEntity> page = this.page( new Page<>(pageNum,pageSize),
                new QueryWrapper<ContractUrlEntity>().eq("oid",oid).orderByDesc("create_time"));
        return new PageResult(page);
    }




    @Override
    public ContractUrlEntity getByIdE(Long id) {
            ContractUrlEntity one = this.getOne(new QueryWrapper<ContractUrlEntity>().eq("id", id).eq("is_delete", 0));

        return one;
    }


    @Override
    public List<ContractUrlEntity> getContractUrlEntityListByIdCardAndStatus(@RequestParam("id") String id) {
        List<ContractUrlEntity> list = contractUrlDao.selectList(new QueryWrapper<ContractUrlEntity>().eq("id_card", id).eq("status",2)
                .eq("is_delete",0).isNotNull("contract_esign_url")
                .isNotNull("contract_oss_url"));
        return list;
    }

    @Override
    public List<ContractUrlEntity> getByIdCard(@RequestParam("id") String id) {
        List<ContractUrlEntity> list = contractUrlDao.selectList(new QueryWrapper<ContractUrlEntity>().eq("id_card", id)
                .eq("is_delete",0).isNotNull("contract_esign_url")
                .isNotNull("contract_oss_url"));
        return list;
    }

    @Override
    public R saveE(ContractUrlEntity entity) {
        boolean b = this.save(entity);
        if (!b){
            return R.error();
        }
        return R.ok();

    }

    @Override
    public R updateByIdE(ContractUrlEntity entity) {
        boolean b = this.updateById(entity);
        if (!b){
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R removeOneById(Long id) {
            ContractUrlEntity entity = new ContractUrlEntity();
        entity.setId(id);
        entity.setIsDelete(1);
        boolean b = this.updateById(entity);
        if (!b){
            return R.error();
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R removeByIdsE(List<Long> ids) {
        for (Long id : ids) {
            R r = removeOneById(id);
            if (!r.getFlag()){
                return r;
            }
        }
        return R.ok();
    }

    @Override
    public R saveContractUrl(@RequestBody ContractUrlEntity contractUrlEntity) throws Exception {

//        String eSignUrl = contractUrlEntity.getContractEsignUrl();
//        Long orderId = contractUrlEntity.getOrderId();

            contractUrlEntity.setCreateTime(new Date());
            this.save(contractUrlEntity);
            return R.ok();


    }

    @Override
    public R<List<ContractUrlEntity>> findByFlowId(@RequestParam("flowId") Integer flowId) {
        List<ContractUrlEntity> flow_id = contractUrlDao.selectList(new QueryWrapper<ContractUrlEntity>().eq("flow_id", flowId)
        );
        return R.ok(flow_id);
    }

    @Override
    public R uploadToOssAndUpdate(@RequestBody ContractUrlEntity contractUrlEntity) throws Exception {


        String eSignUrl = contractUrlEntity.getContractEsignUrl();
        String idCard = contractUrlEntity.getIdCard();



        InputStream inputStream = IoUtils.getInputStreamByUrl(eSignUrl);
        String upload = ossUploadService.upload(inputStream, "contract",idCard+".pdf");


        contractUrlEntity.setContractOssUrl(upload);

        this.updateById(contractUrlEntity);




        return R.ok();
    }




}